package com.example.pool;

import java.util.concurrent.*;

/**
 * @author zhangs
 * @version v1.0
 * @decription 线程池监控
 * @date 2021/4/7 23:14
 **/
public class MonitorTP extends ThreadPoolExecutor {
    public MonitorTP(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    public MonitorTP(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
    }

    public MonitorTP(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
    }

    public MonitorTP(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }

    private String format() {
        String res = String.format("taskCount：%d , " +
                        "completedTaskCount：%d ," +
                        "largestPoolSize: %d ," +
                        "getPoolSize：%d ," +
                        "getActiveCount:%d ",
                getTaskCount(),
                getCompletedTaskCount(),
                getLargestPoolSize(),
                getPoolSize(),
                getActiveCount());
        return res;
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        System.out.println("before:\n\t" + format());
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        System.out.println("after:\n\t" + format());
    }

    @Override
    protected void terminated() {
        System.out.println("terminated:\n\t" + format());
    }
}
